<template>
  <div id="hello" >
      <select id='sel' @change="changeLayout()" style="width:250px;height:23px">             
          <option :value='item.value' v-for="item in LayoutOptions" :key="item.value">{{item.label}}</option>
          
      </select>  
  </div>
</template>

  <script lang="ts">
  import { Component, Prop, Vue } from 'vue-property-decorator';
  import {topology} from '../views/topology'




  var CreateEdgeInteractor :any= function(graphView) {
      CreateEdgeInteractor.superClass.constructor.call(this, graphView);
  };
  @Component
 
  export default class HelloWorld extends Vue {
    
    private _expand:boolean=false
    private LayoutValue:string='circular'
    private LayoutOptions:Array<any>=[
      {
          value: 'circular',
          label: '圆形布局'
        }, {
          value: 'symmetric',
          label: '对称布局'
        }, {
          value: 'towardnorth',
          label: '朝北布局'
        }, {
          value: 'towardsouth',
          label: '朝南布局'
        }, {
          value: 'towardeast',
          label: '朝东布局'
        }, {
          value: 'towardwest',
          label: '朝西布局'
        }
    ]
    private dataModel:any = null   //创建一个 ht
    private graphView:any = null   //构造函数传入其所绑定的组件对象
    private borderPane:any = null   //创建工具条
    private autoLayout:any = null   //自动布局
    private overview:any = null  //鹰眼
    private clicknode:any=null //点击操作的节点
    private clicklink:any=null //点击操作的线
    
    private contextmenu:any=null  //右键菜单

    private copydata:any=null
    private eventdata:any=null //点击背景获得的event

   

    public mounted() {
      this.initHT()
    }
    public created() {
      
    }

    //布局改变
    private changeLayout(){
      var sel:any=document.getElementById('sel')
        this.layout(sel.value);
    }
    private initHT(){
        var that=this

        //这个是 连线的操作
        ht.Default.def(CreateEdgeInteractor, ht.graph.Interactor, {
            setUp: function() {
                CreateEdgeInteractor.superClass.setUp.call(this);
                this._autoMakeVisible = this._graphView.isAutoMakeVisible();
                this._graphView.setAutoMakeVisible(false);
            },
            tearDown: function() {
                CreateEdgeInteractor.superClass.tearDown.call(this);
                this._graphView.setAutoMakeVisible(this._autoMakeVisible);
                this._graphView.getSelectionModel().clearSelection();
            },
            handle_mousedown: function(e) {
                this.handle_touchstart(e);
            },
            handle_touchstart: function(e) {
                this._sourceNode = this.getNodeAt(e);
                if (this._sourceNode) {
                    this._targetNode = null;
                    this.startDragging(e);
                    this._graphView.addTopPainter(this);
                    this._graphView.getSelectionModel().setSelection(this._sourceNode);
                }
            },
            getNodeAt: function(e) {
                if (ht.Default.isLeftButton(e) && ht.Default.getTouchCount(e) === 1) {
                    var data = this._graphView.getDataAt(e);
                    if (data instanceof ht.Node) {
                        return data;
                    }
                }
                return null;
            },
            handleWindowMouseMove: function(e) {
                this.handleWindowTouchMove(e);
            },
            handleWindowMouseUp: function(e) {
                this.handleWindowTouchEnd(e);
            },
            handleWindowTouchMove: function(e) {
                var graphView = this._graphView;
                this.redraw();
                this._logicalPoint = graphView.getLogicalPoint(e);
                this.autoScroll(e);
                this._targetNode = this.getNodeAt(e);
                if (this._targetNode) {
                    graphView.getSelectionModel().setSelection([this._sourceNode, this._targetNode]);
                } else {
                    graphView.getSelectionModel().setSelection([this._sourceNode]);
                }
                this.redraw();
            },
            handleWindowTouchEnd: function(e) {
                this.redraw();
                if (this._targetNode) {
                    var edge = new ht.Edge(this._sourceNode, this._targetNode);
                    edge.setParent(this._graphView.getCurrentSubGraph());
                    this._graphView.getDataModel().add(edge);
                    this._graphView.getSelectionModel().setSelection(edge);
                }
                this._graphView.removeTopPainter(this);
            },
            redraw: function() {
                var p1 = this._sourceNode.getPosition(),
                    p2 = this._logicalPoint;
                if (p1 && p2) {
                    var rect = ht.Default.unionPoint(p1, p2);
                    ht.Default.grow(rect, 1);
                    this._graphView.redraw(rect);
                }
            },
            draw: function(g) {
                var p1 = this._sourceNode.getPosition(),
                    p2 = this._logicalPoint;
                if (p1 && p2) {
                    g.lineWidth = 1;
                    g.strokeStyle = '#1ABC9C';
                    g.beginPath();
                    g.moveTo(p1.x, p1.y);
                    g.lineTo(p2.x, p2.y);
                    g.stroke();
                }
            }
        });

        //这个是鹰眼的  缩放显示
        var ToggleOverview:any  = function(graphView) {
          var self:any  = this;
          ToggleOverview.superClass.constructor.apply(self, [graphView]);                
          self._expand = true;
          
          var div:any  = document.createElement("div");
          div.style.setProperty("width", "24px", null);
          div.style.setProperty("height", "24px", null);
          div.style.setProperty("position", "absolute", null);
          div.style.setProperty("right", "0", null);
          div.style.setProperty("top", "0", null);
          div.style.setProperty("background", `url(${require('../assets/htimg/shrink.png')}) no-repeat`, null);
          div.style.setProperty("background-position", "center center", null);                
          self._view.appendChild(div);
          
          function handleTransitionEnd(e) {
              if (e.propertyName === "width"){
                  self.invalidate();
              }                    
          }
          self._view.addEventListener("webkitTransitionEnd", handleTransitionEnd, false);
          self._view.addEventListener("transitionend", handleTransitionEnd, false);
          var eventName :any = ht.Default.isTouchable ? "touchstart" : "mousedown";
          div.addEventListener(eventName, function(e) {
              if (self._expand) {
                  self._view.style.setProperty("width", "24px", null);
                  self._view.style.setProperty("height", "24px", null);
                  self._canvas.style.setProperty("opacity", "0", null);
                  self._mask.style.setProperty("opacity", "0", null);
                  div.style.setProperty("background-image", `url(${require('../assets/htimg/expand.png')})`, null);
                  div.style.setProperty("width", "24px", null);
                  div.style.setProperty("height", "24px", null);
                  self._expand = false;
              } else {
                  self._view.style.setProperty("width", "", null);
                  self._view.style.setProperty("height", "", null);
                  self._canvas.style.setProperty("opacity", "1", null);
                  self._mask.style.setProperty("opacity", "1", null);
                  div.style.setProperty("background-image", `url(${require('../assets/htimg/shrink.png')})`, null);
                  div.style.setProperty("width", "24px", null);
                  div.style.setProperty("height", "24px", null);
                  self._expand = true;
              }                    
              self.invalidate();                     
              e.stopPropagation();
          });
          self.setContentBackground("white");
      };
      ht.Default.def(ToggleOverview, ht.graph.Overview, {                
      });


      var div:any = document.getElementById("hello");  //获取ht所要放的div
      // var dataModel:any = new ht.DataModel()   //创建一个 ht
      // var graphView:any = new ht.graph.GraphView(dataModel)   //构造函数传入其所绑定的组件对象
      // var borderPane = new ht.widget.BorderPane();   //创建工具条
      // var autoLayout = new ht.layout.AutoLayout(graphView);    //自动布局
      // var overview = new ToggleOverview(graphView)  //鹰眼
      this.dataModel = new ht.DataModel()   //创建一个 ht
      this.graphView = new ht.graph.GraphView(this.dataModel)   //构造函数传入其所绑定的组件对象
      this.borderPane = new ht.widget.BorderPane();   //创建工具条
      this.autoLayout = new ht.layout.AutoLayout(this.graphView);    //自动布局
      this.overview = new ToggleOverview(this.graphView)  //鹰眼

      
      this.borderPane.setTopView(this.createToolbar())                              
  
      this.dataModel.deserialize(topology);    // 渲染数据

      //给每个功能加个class名
      this.graphView.getView().className = 'main';    
      this.overview.getView().className = "overview animation";
      this.borderPane.getView().className = 'toolbar';

     //添加进容器
      div.appendChild(this.graphView.getView());
      div.appendChild(this.overview.getView());
      div.appendChild(this.borderPane.getView())

      this.contextmenu = new ht.widget.ContextMenu();   //创建一个右键弹框
      this.contextmenu.enableGlobalKey();

      var json1:Array<any> =[
          {
              label: "复制",
              action:()=>{
                 this.copydata=this.clicknode
              }
          },
          {
              label: "删除",
              action:(e)=>{
                console.log(this.clicknode) 
                this.dataModel.remove(this.clicknode)
                
              }
          }
      ];
      var json2:Array<any> =[
            {
                label: "删除",
                action:()=>{
                  this.dataModel.remove(this.clicklink)
                }
            }
        ];
      var json3:Array<any>=[
          {
              label: "粘贴",
              action:()=>{
                if(this.copydata){
                    var lp =this.graphView.lp(this.eventdata) //根据点击获得的 eventdata  来获得距离中心的距离
                    var node = new ht.Node();  //创建一个节点
                    node.setName(this.copydata._name)
                    node.setPosition(lp.x, lp.y);  //设置图元中心点坐标
                    this.dataModel.add(node);  //添加节点
                }
              }
          },
      ]
    
      this.contextmenu.beforeShow = function(e) {
          var data = that.graphView.getDataAt(e);
          if (data===undefined) {   //判断点击的是什么    undefined  是背景
              this.setItems(json3); //添加弹框内容
          }else if(data._name){  
            that.clicknode=data
              this.setItems(json1);   //添加弹框内容
              
          }else if(data._source!==null){   
              that.clicklink=data
              this.setItems(json2);//添加弹框内容
          }

      }
      this.contextmenu.addTo(this.graphView.getView());  //添加右击弹框

      window.addEventListener('resize', (e)=>{
          this.graphView.invalidate();
          this.borderPane.invalidate();
      }, false);

      this.graphView.addInteractorListener(function (e) {
        if(e.kind === 'clickData'){   //单击
            that.clicknode=e         
        }
        // else if(e.kind === 'doubleClickData'){
        //     console.log(e.data + '被双击');
        // }            
        else if(e.kind === 'clickBackground'){   //点击背景
            that.eventdata=e.event
        }  
        // else if(e.kind === 'doubleClickBackground'){
        //     console.log('双击背景');
        // }     
        // else if(e.kind === 'beginRectSelect'){
        //     console.log('开始框选图元');
        // }              
        // else if(e.kind === 'betweenRectSelect'){
        //     console.log('正在框选图元');
        // }             
        // else if(e.kind === 'endRectSelect'){
        //     console.log('结束框选图元');
        // }           
        // else if(e.kind === 'beginMove'){
        //     console.log('开始移动图元');
        // }              
        // else if(e.kind === 'betweenMove'){
        //     console.log('正在移动图元');
        // }             
        // else if(e.kind === 'endMove'){
        //     console.log('结束移动图元');
        // } 
        // else if(e.kind === 'beginPan'){
        //     console.log('开始手抓图平移');
        // }              
        // else if(e.kind === 'betweenPan'){
        //     console.log('正在手抓图平移');
        // }             
        // else if(e.kind === 'endPan'){
        //     console.log('结束手抓图平移');
        // }     
        // else if(e.kind === 'beginEditRect'){
        //     console.log('开始编辑图元大小和位置');
        // }              
        // else if(e.kind === 'betweenEditRect'){
        //     console.log('正在编辑图元大小和位置');
        // }             
        // else if(e.kind === 'endEditRect'){
        //     console.log('结束编辑图元大小和位置');
        // } 
        // else if(e.kind === 'beginEditPoint'){
        //     console.log('开始编辑多边形Shape或多点Edge的具体点');
        // }              
        // else if(e.kind === 'betweenEditPoint'){
        //     console.log('正在编辑多边形Shape或多点Edge的具体点');
        // }             
        // else if(e.kind === 'endEditPoint'){
        //     console.log('结束编辑多边形Shape或多点Edge的具体点');
        // } 
        // else if(e.kind === 'beginEditRotation'){
        //     console.log('开始旋转图元');
        // }              
        // else if(e.kind === 'betweenEditRotation'){
        //     console.log('正在旋转图元');
        // }             
        // else if(e.kind === 'endEditRotation'){
        //     console.log('结束旋转图元');
        // }               
        // else if(e.kind === 'moveLeft'){
        //     console.log('左方向键左移图元一个像素');
        // }       
        // else if(e.kind === 'moveRight'){
        //     console.log('右方向键右移图元一个像素');
        // } 
        // else if(e.kind === 'moveUp'){
        //     console.log('上方向键上移图元一个像素');
        // } 
        // else if(e.kind === 'moveDown'){
        //     console.log('下方向键下移图元一个像素');
        // } 
        // else if(e.kind === 'toggleNote'){
        //     console.log('切换note标注的展开合并');
        // }             
        // else if(e.kind === 'toggleNote2'){
        //     console.log('切换note2标注的展开合并');
        // }
        // else if(e.kind === 'beginEditPoints'){
        //     console.log('开始进入曲线的点编辑状态');
        // }
        // else if(e.kind === 'endEditPoints'){
        //     console.log('结束曲线的点编辑状态');
        // } 
        // else if(e.kind === 'hover'){
        //     console.log('鼠标停留');
        // } 
        // else if(e.kind === 'onClick'){
        //     console.log('单击图元');
        // } 
        // else if(e.kind === 'onDoubleClick'){
        //     console.log('双击图元');
        // } 
        // else if(e.kind === 'onContextMenu'){
        //     console.log('右击图元');
        // } 
        // else if(e.kind === 'onDown'){
        //     console.log('在图元处按下');
        // } 
        // else if(e.kind === 'onUp'){
        //     console.log('在图元处放开');
        // } 
        // else if(e.kind === 'onMove'){
        //     console.log('鼠标在图元上移动');
        // } 
        // else if(e.kind === 'onEnter'){
        //     console.log('鼠标进入图元');
        // } 
        // else if(e.kind === 'onHover'){
        //     console.log('鼠标在图元上悬停');
        // } 
        // else if(e.kind === 'onLeave'){
        //     console.log('鼠标离开图元');
        // } 
        // else if(e.kind === 'onBeginDrag'){
        //     console.log('图元开始拖拽');
        // } 
        // else if(e.kind === 'onDrag'){
        //     console.log('图元拖拽');
        // } 
        // else if(e.kind === 'onEndDrag'){
        //     console.log('图元结束拖拽');
        // } 
        // else if(e.kind === 'onScroll'){
        //     console.log('鼠标图元上滚动');
        // } 
    });

      this.layout('circular');   //初始化布局
    }

    //工具条
     createToolbar(){
        var  that=this
        var toolbar = new ht.widget.Toolbar([
            {
                icon: `${require('../assets/htimg/zoomIn.png')}`,  
                action: function() {
                    that.graphView.zoomIn(true);  //放大
                }
            },
            {
                icon: `${require('../assets/htimg/zoomOut.png')}`,
                action: function() {
                    that.graphView.zoomOut(true);//缩小
                }
            },
            {
                icon: `${require('../assets/htimg/fitContent.png')}`,
                action: function() {
                    that.graphView.fitContent(true);//恢复中心点布局
                }
            },
            'separator',
            {
                icon: `${require('../assets/htimg/default.png')}`,
                groupId: 'interaction',
                action: function() {
                    that.graphView.setEditable(false); //只有拖拽的操作
                }
            },
            {
                icon: `${require('../assets/htimg/edit.png')}`,
                groupId: 'interaction',
                action: function() {
                    that.graphView.setEditable(true);  //可以拖拽  可以改变节点大小 方向等
                }
            },
            {
                icon: `${require('../assets/htimg/edge.png')}`,
                groupId: 'interaction',
                action: function() {             //节点之间的连线
                    that.graphView.setInteractors([
                        new ht.graph.DefaultInteractor(that.graphView),
                        new ht.graph.TouchInteractor(that.graphView, {
                            selectable: false
                        }),
                        new CreateEdgeInteractor(that.graphView)
                    ]);;
                }
            },"separator",
            {
                label: 'Image',
                action: function() {           //截图
                    var doc = window.open().document;
                    doc.open();
                    doc.write("<img src='" + that.graphView.toDataURL() + "'/>");
                    doc.close();
                    doc.body.style.margin = '0';
                    doc.title = 'Export image at ' + new Date();
                }
            },
            {
                label: 'JSON',
                action: function() {       //数据
                    var doc = window.open().document;
                    doc.open();
                    doc.write("<pre>" + that.dataModel.serialize() + "</pre>");
                    doc.close();
                    doc.body.style.margin = '0';
                    doc.title = 'Export JSON at ' + new Date();
                }
            },
            'separator',
            {      
                id: 'nation',
                label: '自动布局：',                        
                element: document.getElementById('sel')
            },
        ]);
        return toolbar;                
    } 
    //自定义布局
    private layout(type){
         this.autoLayout.layout(type, ()=>{
              this.graphView.fitContent(true);
          });
      } 
  }


  
  </script>

  <style >
    #hello{
      margin: 0;
      padding: 0;
      height: 95vh;
      width: 100vw;
      position: relative;
    }
    .main {
        margin: 0px;
        padding: 0px;
        position: absolute;
        top: 30px;
        left: 0px;
        height: 93vh;
        width: 100vw;
    }
    .overview{
        position:absolute;
        left:0px;
        bottom:0px;
        width:200px;
        height:150px;
        background:rgb(240, 239, 248);
    }
    .toolbar{
      margin: 0px;
      padding: 0px;
      position: absolute;
      top: 0px;
      left: 0px;
      height: 30px;
      width: 100%;

    }
    .animation{
        -webkit-transition: width .3s,height .3s;
        -moz-transition: width .3s,height .3s;
        -o-transition: width .3s,height .3s;
        transition: width .3s,height .3s;
    }
    .element.style{
      position: static;
    }
  </style>
